/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ru.dusty.fs.filesystem.data;

import java.io.File;
import java.io.IOException;
import ru.dusty.fs.filesystem.utils.Utils;

/**
 *
 * @author Dusty
 */
public class BlocksMap {
    
    private boolean[] map;
    
    private String root;
    
    private int count;
    
    public BlocksMap(String root, int blocksCount) {
        this.root = root;
        this.count = blocksCount;
        
        if (blocksCount < 1) count = Utils.FS_MAX_SIZE / Utils.BLOCK_MIN_SIZE;
    }
    
    public void initMap() throws IOException {
        map = new boolean[count];
        initMapForBlock(1);
    }
    
    private void initMapForBlock(int number) throws IOException {
        File file = new File(root + File.separator + number);
        
        MetaData metaData;
        if (number == 1) {
            metaData = new SuperBlock();
        } else {
            metaData = new MetaData();
        }
        
        Block block = new Block(file, "r");
            
        block.readMetaData(metaData);
        
        map[number - 1] = true;
        int nextBlock;
        
        if (metaData.getType().equals(BlockType.FOLDER)) {
            int filesCount = metaData.getSize();
            block.seek(metaData.getMetaDataSize());
            do {    
                nextBlock = block.getNextBlock();
                while (filesCount != 0 && block.hasMoreInt()) {
                    int val = block.read();
                    if (val != 0) {
                        filesCount--;
                        initMapForBlock(val);
                    } 
                }
                
                block.close();
                if (nextBlock != 0 && filesCount != 0) {
                    block = new Block(new File(root + File.separator + nextBlock), "r");

                    map[nextBlock - 1] = true;
                    block.seek(0);
                }
            } while (nextBlock != 0 && filesCount != 0);
        } else {
            nextBlock = block.getNextBlock();
            while (nextBlock != 0) {
                block.close();
                block = new Block(new File(root + File.separator + nextBlock), "r");
                
                map[nextBlock - 1] = true;
                nextBlock = block.getNextBlock();
            }
        }   
    }
    
    public int allocateBlock() {
        if (map == null) return -1;
        
        for (int i = 0; i < map.length; i++) {
            if (!map[i]) {
                map[i] = true;
                return i + 1;
            }
        }
        
        return -1;
    }
    
    public void deallocateBlock(int i) {
        map[i - 1] = false;
    }
    
}
